﻿using PLCS.Domain.Orders;
using PLCS.Domain.Shared.Orders;
using PLCS.Shared.Common.Constant;

using Polly;

using Volo.Abp.Domain.Repositories;

namespace PLCS.Web.EventHandlers;

public class OrderFinshEventHandler : ILocalEventHandler<OrderFinshEvent>, ITransientDependency
{
    private readonly IRepository<Order> _orderRepo;
    private readonly IRepository<HisOrder> _hisOrderRepo;
    private readonly ILogger<OrderFinshEventHandler> _logger;

    public OrderFinshEventHandler(IRepository<Order> orderRepo, IRepository<HisOrder> hisOrderRepo,
        ILogger<OrderFinshEventHandler> logger)
    {
        _orderRepo = orderRepo;
        _hisOrderRepo = hisOrderRepo;
        _logger = logger;
    }

    public async Task HandleEventAsync(OrderFinshEvent eventData)
    {
        try
        {
            _logger.LogInformation($"订单'{eventData.OrderNo}'执行完成，开始从当前订单表中删除，存入历史订单表中");
            var order = await _orderRepo.GetAsync(x => x.Id == eventData.Id);
            await _orderRepo.DeleteAsync(order);

            await _hisOrderRepo.InsertAsync(new HisOrder(pdLineNo: eventData.LineNo,
                trayNo: eventData.OrderNo,
                orderNo: eventData.OrderNo,
                orderType: eventData.OrderType,
                onlineStation: eventData.OnlineStation,
                planStartTime: eventData.PlanStartTime,
                planEndTime: eventData.PlanEndTime,
                factStartTime: (DateTime)eventData.FactStartTime,
                solutionNo: eventData.SolutionNo,
                eventData.UpperNo));
            _logger.LogInformation($"订单'{eventData.OrderNo}'执行完成，从当前订单表中删除成功，存入历史订单表中");
        }
        catch (Exception ex)
        {
            _logger.LogError($"订单'{eventData.OrderNo}'执行完成，从当前订单表中删除失败", ex);
        }
    }
}